using System;
using System.Collections;
using System.Collections.Generic;

namespace Mbs.Elements
{
    [Serializable]
    class ElementCategory : MarshalAndDisposableObject, IElementCategory
	{
		IElement element;
        List<IElement> items = new List<IElement>();

        public ElementCategory(IElement element)
		{
			this.element = element;
		}

		public int Count
		{
			get { return items.Count; }
		}

		public IElementCommand Add<TUIElement>(TUIElement uiElement, string commandName)
		{
			element.Add(uiElement);

            var elementService = ServiceLocator.Current.Get<IElementService>();
            var childElement = elementService.ElementMap.Register(uiElement);

            if (!string.IsNullOrEmpty(commandName))
            {
                childElement.Commands.Add(commandName);
                items.Add(childElement);
                return commandName.Command();
            }

            return null;
		}

		public void Clear()
		{
            foreach (var obj in items)
            {
                obj.Remove(obj.Target);
                element.Remove(obj.Target);
            }

			items.Clear();
		}

        public IElement GetElement(object uiElement)
        {
            foreach (var e in items)
                if (object.ReferenceEquals(uiElement, e.Target))
                    return e;
            return null;
        }

		public bool Contains(object uiElement)
		{
            return GetElement(uiElement) != null;
		}

		public void Remove(object uiElement)
		{
            var e = GetElement(uiElement);
            if (e != null)
            {
                e.Remove(uiElement);
                element.Remove(uiElement);
                items.Remove(e);
            }
		}

        protected override void Dispose(bool disposing)
        {
            Clear();
        }
		
        IEnumerator<IElement> IEnumerable<IElement>.GetEnumerator()
		{
			return items.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return items.GetEnumerator();
		}
	}
}
